#version 410

out vec4 fragCol;


struct PointLight 
{
	float ambientIntensity;
	float diffuseIntensity;
	float specularIntensity;
	float specularPower;
	vec3 color;
	vec3 position;
	float attConstant;
	float attLinear;
	float attExp;
};


uniform PointLight light;
uniform sampler2D shadowMap;
uniform sampler2D worldPosMap;
uniform sampler2D diffuseMap;
uniform sampler2D normalMap;

uniform vec2 screenSize;
uniform vec3 eyeWorldPos;

vec2 getTexCoord()
{
   return gl_FragCoord.xy / screenSize;
}

vec4 getLightInfluence(vec3 worldPos, vec3 norm)
{
	vec3 lightDirection = worldPos - light.position;
	float distance = length(lightDirection);
	lightDirection = normalize(lightDirection);

	vec4 ambientColor = vec4(light.color, 1.0f) * light.ambientIntensity;
	float diffuseFactor = dot(norm, -lightDirection);

	vec4 diffuseColor  = vec4(0, 0, 0, 0);
	vec4 specularColor = vec4(0, 0, 0, 0);

	if (diffuseFactor > 0) 
	{
		diffuseColor = vec4(light.color, 1.0f) * light.diffuseIntensity * diffuseFactor;
        vec3 vertexToEye = normalize(eyeWorldPos - worldPos);
        vec3 lightReflect = normalize(reflect(lightDirection, norm));
        float specularFactor = dot(vertexToEye, lightReflect);
		specularFactor = pow(specularFactor, light.specularPower);
		if (specularFactor > 0)
		{
			specularColor = vec4(light.color, 1.0f) * light.specularIntensity * specularFactor;
		}
	}

	vec4 color = (ambientColor + diffuseColor + specularColor);

	// Spot light attenuation formula
	float attenuation =  light.attConstant + light.attLinear * distance + light.attExp * distance * distance;

	return color / attenuation;
}

void main()
{
	vec2 texCoord = getTexCoord();
    vec4 worldPos = texture(worldPosMap, texCoord);
    vec4 color = texture(diffuseMap, texCoord);
    vec4 normal = texture(normalMap, texCoord);

	fragCol = vec4(color.rgb, 1.0) * getLightInfluence(worldPos.xyz, normal.xyz);
}